<script setup lang="ts">
import type { FieldRule, FormInstance } from 'vant'
import { ref } from 'vue'

/*
vant表单验证
1:布局
2：表单元素值绑定
3:给每一个表单元素写验证规则
   van-field
      :rules=[
        {required:true,message:'错误信息',trigger:'onBlur/onChange'},
        {pattern:正则,message:'错误信息',trigger:'onBlur/onChange'}
        ....
      ]
4:全局表单验证处理
   van-form上的一个validate方法

*/
const state = ref<{
  username: string
  password: string
}>({
  username: '',
  password: ''
})

const rules: {
  username: FieldRule[]
  password: FieldRule[]
} = {
  username: [{ required: true, message: '必填', trigger: 'onChange' }],
  password: [{ required: true, message: '必填', trigger: 'onChange' }]
}
const form = ref<FormInstance>()
const submit = async () => {
  try {
    await form.value?.validate()
    // 成功
    console.log('成功')
  } catch {
    console.log('失败')
  }
}
</script>

<template>
  <van-form ref="form">
    <van-field :rules="rules.username" label="用户名" v-model="state.username"></van-field>
    <van-field :rules="rules.password" label="密码" v-model="state.password"></van-field>
  </van-form>
  <van-button @click="submit">登录</van-button>
</template>

<style scoped></style>
